Native methods are functions that reside in libraries outside the .NET runtime. Calling them is helpful for interoperability with applications and
libraries written in other programming languages, mainly when performing platform-specific operations. However, doing so comes with additional risks
since it means stepping out of the memory-safety model of the runtime. It is therefore highly recommended to take extra steps, like input validation,
when invoking native methods. Making the native method private
and providing a wrapper that performs these additional steps is the best
way to do so.
This rule raises an issue when a native method is declared public
or its wrapper is too trivial.
Noncompliant code example
using System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
class Foo
{
[DllImport("mynativelib")]
extern public static void Bar(string s, int x); // Noncompliant
}
}
Compliant solution
using System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
class Foo
{
[DllImport("mynativelib")]
extern private static void Bar(string s, int x);
public void BarWrapper(string s, int x)
{
if (s != null && x >= 0 && x < s.Length)
{
Bar(s, x);
}
}
}
}